package com.dempsey.springboot06securityjwtredis.project.controller;

import com.dempsey.springboot06securityjwtredis.framework.entity.LoginUser;
import com.dempsey.springboot06securityjwtredis.framework.security.service.TokenService;
import com.dempsey.springboot06securityjwtredis.framework.web.domain.JsonResult;
import com.dempsey.springboot06securityjwtredis.project.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Dempsey
 * Date 2022/2/9
 * Description
 */

@RestController
public class RouterController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @GetMapping("/index")
    public JsonResult index() {
        return JsonResult.success("index");
    }

    @PostMapping("/login")
    public JsonResult login(@RequestBody User user) {
        // 登录逻辑
        // 1、去数据库中找
        // 2、生成token并返回
        Authentication authentication;

        // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
        // 此处并没有把认证信息 加入到 SecurityContextHolder中，只是自定义认证通过了，那么会把token 信息返回，之后的认证都基于token
        authentication = authenticationManager
                .authenticate(new UsernamePasswordAuthenticationToken(user.getName(), user.getPwd()));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String token = tokenService.createToken(loginUser);

        return JsonResult.success(token);
    }

    @PreAuthorize("hasAuthority('vip1')")
    @GetMapping("/vip1")
    public JsonResult vip1() {
        return JsonResult.success("vip1");
    }

    @PreAuthorize("hasAuthority('vip2')")
    @GetMapping("/vip2")
    public JsonResult vip2() {
        return JsonResult.success("vip2");
    }

}
